from docx import Document
from PIL import Image, ImageDraw, ImageFont

def calculate_text_bbox(text, font, max_width):
    # 创建一个虚拟的图像
    img = Image.new('RGB', (max_width, 100), color=(255, 255, 255))
    draw = ImageDraw.Draw(img)

    # 使用给定的字体和文本获取文本的边界框
    text_bbox = draw.textbbox((0, 0), text, font=font)

    return text_bbox

def docx_to_image(docx_path, img_path, font_path='path/to/your/font.ttf', font_size=20, line_spacing=1.5):
    """
    将Word文档转换为单张图片，自动适应文档长度

    :param docx_path: Word文档的路径
    :param img_path: 输出图片的保存路径
    :param font_path: 使用的字体路径
    :param font_size: 字体大小
    :param line_spacing: 行间距
    """
    # 载入文档
    doc = Document(docx_path)

    # 准备字体
    font = ImageFont.truetype(font_path, font_size)

    # 计算文档内容所需的总高度
    doc_height = 0
    max_text_width = 0  # 记录最大文本宽度
    for para in doc.paragraphs:
        if para.text:
            # 使用Pillow的textbbox方法获取文本的边界框
            text_bbox = calculate_text_bbox(para.text, font, 800)
            text_height = text_bbox[3] - text_bbox[1]  # 计算高度
            doc_height += text_height * line_spacing

            text_width = text_bbox[2] - text_bbox[0]  # 计算宽度
            if text_width > max_text_width:
                max_text_width = text_width

    # 根据文本的最大宽度来确定图片的宽度
    img_width = int(max_text_width + 20)  # 增加一些边距
    img = Image.new('RGB', (img_width, int(doc_height)), color=(255, 255, 255))
    d = ImageDraw.Draw(img)

    # 在图片上写入文本
    current_height = 0
    for para in doc.paragraphs:
        if para.text:
            # 使用Pillow的textbbox方法获取文本的边界框
            text_bbox = calculate_text_bbox(para.text, font, img_width)
            text_height = text_bbox[3] - text_bbox[1]  # 计算高度
            d.text((10, current_height), para.text, fill=(0, 0, 0), font=font)
            current_height += text_height * line_spacing

    # 保存图片到文件
    img.save(img_path)

# 使用示例
docx_to_image('C:/Users/yra/Desktop/MathVecCluster/data/docx/2019年北京市中考数学试卷pdf2word.docx', 'C:/Users/yra/Desktop/MathVecCluster/data/image/2019年北京市中考数学试卷pdf2word.png', 'C:/Users/yra/Desktop/MathVecCluster/resource/fonts/Microsoft YaHei.ttf', 20)
